package com.example.andoidepubziputil;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import com.example.ListItems.mArrAdapter;
import com.example.ListItems.mListItem;
import com.example.lib.AsynCollect;
import com.example.lib.AsynDecompress;
import com.example.lib.CollectEpub;
import com.example.lib.Decompress;
import com.example.lib.EpubUTIL;

import com.google.gson.Gson;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {

	ListView list_item;
	ArrayList<String> arrFile = new ArrayList<String>();
	Gson gson = new Gson();
	EditText search;
	mArrAdapter marr;
	ImageView clearbut;
	ImageView refreshbut;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		list_item = (ListView) findViewById(R.id.list_epub);
		search = (EditText) findViewById(R.id.search_book);
		clearbut = (ImageView) findViewById(R.id.but_clear);
		refreshbut = (ImageView) findViewById(R.id.but_refresh);
		clearbut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				search.setText("");

			}
		});
		refreshbut.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				new AsynCollect(MainActivity.this, Environment
						.getExternalStorageDirectory(), _collectEpub).execute();
			}
		});
		search.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
				marr.getFilter().filter(s);

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub

			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub

			}
		});
		list_item.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> list, View view,
					int position, long arg) {
				File file = new File(arrFile.get(position));

				if (file.exists()) {

					Intent i = new Intent(MainActivity.this, Unzip.class);
					Bundle bundle = new Bundle();
					Log.v("BOOK", arrFile.get(position));

					bundle.putString("EpubURL", arrFile.get(position));
					i.putExtras(bundle);
					startActivity(i);
					return false;
				} else {
					return false;
				}
			}

		});
		try {

			File files = new File(EpubUTIL.ROOT_CATCHEPUB);

			if (files.exists()) {
				String results = ReadTxt(EpubUTIL.ROOT_CATCHEPUB);
				ArrayList<String> arr = gson.fromJson(results, ArrayList.class);
				ArrayList<mListItem> arrm = new ArrayList<mListItem>();
				arrm.clear();
				arrFile.clear();
				for (String a : arr) {

					File file = new File(a);

					Bitmap bm = BitmapFactory.decodeResource(getResources(),
							R.drawable.epubicon);

					mListItem it1;
					arrFile.add(a);
					if (file.exists()) {

						it1 = new mListItem(file.getName(), String.valueOf(file
								.length()) + " bytes", bm);
						Log.v("Name", file.getAbsolutePath());
					} else {
						it1 = new mListItem("File Not Found !! ", a, bm);
					}

					arrm.add(it1);
				}
				marr = new mArrAdapter(MainActivity.this, arrm, 0);

				list_item.setAdapter(marr);
			} else {

				// new Thread(ACTIVITY_SERVICE){
				// public void run() {
				// ArrayList<String> add =
				// CollectEpub.walkdir(Environment.getExternalStorageDirectory());
				//
				// }
				//
				// }.start();
				new AsynCollect(MainActivity.this,
						Environment.getExternalStorageDirectory(), _collectEpub)
						.execute();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		return MenuChoice(item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		CreateMenu(menu);
		return true;
	}

	private boolean MenuChoice(MenuItem item) {
		switch (item.getGroupId()) {

		case 1: {

			new AsynCollect(MainActivity.this,
					Environment.getExternalStorageDirectory(), _collectEpub)
					.execute();
			return true;
		}
		case 2: {
			android.os.Process.killProcess(android.os.Process.myPid());
			return true;
		}
		}
		return false;
	}

	private void CreateMenu(Menu menu) {
		menu.clear();

		MenuItem mnu1 = menu.add(1, 0, 0, "Refresh List");
		MenuItem mnu2 = menu.add(2, 0, 0, "Exit");

	}

	public String ReadTxt(String URL) throws IOException {

		String result = "";
		BufferedReader in = new BufferedReader(new FileReader(URL));
		String line;
		while ((line = in.readLine()) != null) {
			result += line;
		}
		return result;
	}

	public void WriteToFile(String result) {
		PrintWriter writer;
		try {

			writer = new PrintWriter(EpubUTIL.ROOT_CATCHEPUB, "UTF-8");

			writer.println(result);

			writer.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	public void getFile(String result) {

		WriteToFile(result);
		ArrayList<String> arr = gson.fromJson(result, ArrayList.class);
		ArrayList<mListItem> arrm = new ArrayList<mListItem>();
		arrFile.clear();
		arrm.clear();
		for (String a : arr) {
			try {
				File file = new File(a);
				arrFile.add(a);

				Bitmap bm = BitmapFactory.decodeResource(getResources(),
						R.drawable.epubicon);

				mListItem it1 = new mListItem(file.getName(),
						String.valueOf(file.length()) + " bytes", bm);
				arrm.add(it1);
				Log.v("Name", file.getCanonicalPath());
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
		marr = new mArrAdapter(MainActivity.this, arrm, 0);

		list_item.setAdapter(marr);
	}

	private Handler _collectEpub = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				Bundle bundle = new Bundle();
				bundle = msg.getData();
				String kq = bundle.getString("list");
				getFile(kq);
			}
			super.handleMessage(msg);
		}

	};

}
